package qldc.pm.qlktcsdldc.portlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;

import qldc.pm.qlktcsdldc.actions.ActionHandlerConstant;
import qldc.pm.qlktcsdldc.actions.DanhMucSoBanNganhAction;
import qldc.pm.qlktcsdldc.actions.ImportDanCuAction;
import qldc.pm.qlktcsdldc.actions.QuanLyDanCuAction;
import qldc.pm.qlktcsdldc.actions.QuanLyTaiKhoanAction;
import qldc.pm.qlktcsdldc.actions.ResourceRequestHandler;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.util.bridges.mvc.MVCPortlet;

public class QLKTCSDLDCPortlet extends MVCPortlet {
	private static Log _log = LogFactoryUtil.getLog(QLKTCSDLDCPortlet.class);

	private static Map<String, Class<?>> resourceActions;

	public static ActionRequest sharedAction;
	
	@Override
	public void init() throws PortletException {
		resourceActions = new HashMap<String, Class<?>>();
		resourceActions.put(ActionHandlerConstant.QUAN_LY_TAI_KHOAN_ACTION, QuanLyTaiKhoanAction.class);
		resourceActions.put(ActionHandlerConstant.QUAN_LY_DAN_CU_ACTION, QuanLyDanCuAction.class);
		resourceActions.put(ActionHandlerConstant.IMPORT_DAN_CU_ACTION, ImportDanCuAction.class);
		resourceActions.put(ActionHandlerConstant.DANH_MUC_SO_BAN_NGANH_ACTION, DanhMucSoBanNganhAction.class);
		
		super.init();
	}

	private Map<String, Class<?>> getResourceActions() {
		return resourceActions;
	}

	@Override
	public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException {
		String actionHandler = ParamUtil.getString(actionRequest, ActionHandlerConstant.ACTION_HANDLER_PARAM);
		String action = ParamUtil.getString(actionRequest, Constants.ACTION);

		try {
			Class<?> clazz = getResourceActions().get(actionHandler);

			Method method = clazz.getMethod(action, ActionRequest.class, ActionResponse.class);

			method.invoke(clazz.newInstance(), actionRequest, actionResponse);
		} catch (Exception e) {
			_log.error(e);
		}
	}

	@Override
	public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
		String resourceId = resourceRequest.getResourceID();
		ResourceRequestHandler loadURLAction = new ResourceRequestHandler();
		Method method = null;
		try {
			method = ResourceRequestHandler.class.getMethod(resourceId, ResourceRequest.class, ResourceResponse.class);
			if(Validator.isNotNull(method)) {
				method.invoke(loadURLAction, resourceRequest, resourceResponse);
			}
		} catch (Exception e) {
			_log.error(e);
		}
	}
}
